package com.ruoyi.system.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Service
@Slf4j
public class MqttClientTest {
//    @PostConstruct
    public void init() throws IOException, MqttException, InterruptedException {
        String brokerUrl = "tcp://localhost:1883";
        String clientId = "moni03";

        // 创建客户端
        MqttClient client = new MqttClient(brokerUrl, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);

        // 连接Broker
        client.connect(options);
        log.info("连接成功");

        // 订阅主题
        client.subscribe("/topic", (topic, message) ->
                log.info("收到消息: " + new String(message.getPayload())));

        // 发布消息
        client.publish("/topic", new MqttMessage("Hello MQTT!".getBytes()));
        client.disconnect();
    }

    public static void main(String[] args) throws MqttException, InterruptedException {
        String brokerUrl = "tcp://172.16.9.7:1883";
        String clientId = "test";
        
        // 创建客户端
        MqttClient client = new MqttClient(brokerUrl, clientId);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);


        // 3. 设置回调（异步接收消息）
        client.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                log.info("连接断开: " + cause.getMessage());
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) {
                log.info("收到消息: ");
                log.info("主题: " + topic);
                log.info("内容: " + new String(message.getPayload()));
                log.info("QoS: " + message.getQos());
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                // 发布消息完成的回调（订阅者无需处理）
            }
        });
        // 4. 连接Broker
        client.connect(options);
        // 订阅主题
        client.subscribe("test/topic", 1);
        while (true) {
            System.out.println("发送消息");
        }
        //         发布消息
//        client.publish("test/topic", new MqttMessage("Hello12312 MQTT!".getBytes()));
//        client.disconnect();
    }
}